<?php
/********************************************************/
/* Module Name: update_frm.php						    */
/* Description: GUI for update case form				 */
/* Written by: Maria Cielo Carreno							*/
/********************************************************/
  define("IDS",1);
  session_start();
//If your session isn't valid, it returns you to the login screen for protection
if(empty($_SESSION['myusername'])){
 header("location:main_login.php");
}
if(empty($_SESSION['seedval'])){
 header("location:main_login.php");
}
//echo $_SESSION['myusername'];
if($_GET['id'] != $_SESSION['seedval'])
{
	echo 'Security breakage!';
	$error = 1;
}
  
 //check code value
  if (!isset($_GET['code']) && !is_numeric($_GET['code']) && $_GET['code'] <= 0)
  {
		header("location:main_login.php");
  }
 //check valid id
   if (!isset($_GET['id']) && !is_numeric($_GET['code']) && $_GET['code'] <= 0)
  {
		header("location:main_login.php");
  }
  
  if(!isset($_GET['case'])){
	header("location:main_login.php");
  }
 function GetTypeCase($val)
 {
  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM typeofcase Order by Tdescription") 
                or die(mysql_error());  
		$select = "<select name=\"typeId\">\n";
		while($row = mysql_fetch_array( $result ))
		{
			if($val == $row['typeId']){
				$select .="\t<option selected='selected'>".$row['Tdescription']."  *".$row['typeId']."</option>\n";
			}
			else{
			   $select .="\t<option>".$row['Tdescription']."   *".$row['typeId']."</option>\n";
			}
		}
		$select .= "</select>";
		echo $select;
 }
 
 
 function GetNatureCase($val)
 {

  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM natureofcase Order by Ndescription") 
                or die(mysql_error());  
		$select = "<select name=\"natureOfCase\">\n";
		while($row = mysql_fetch_array( $result ))
		{
			if($val == $row['code']){
				$select .="\t<option selected='selected'>".$row['Ndescription']."  *".$row['code']."</option>\n";
			}
			else{
				$select .="\t<option>".$row['Ndescription']."   *".$row['code']."</option>\n";
			}
		}
		$select .= "</select>";
		echo $select;
 }
 
 function GetMediator($val)
 {
  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM mediator Order by mediatorName") 
                or die(mysql_error());  
		$select = "<select name=\"mediatorId\">\n";
		while($row = mysql_fetch_array( $result ))
		{
			if($val == $row['mediatorId']){
				$select .="\t<option selected='selected'>".$row['mediatorName']."   *".$row['mediatorId']."</option>\n";
			}
			else{		
				$select .="\t<option>".$row['mediatorName']."   *".$row['mediatorId']."</option>\n";
			}
		}
		$select .= "</select>";
		echo $select;
 }
 
 function GetJudge($val)
 {
  // connect to the database
        include('connect-db.php');
		// get results from database
        $result = mysql_query("SELECT * FROM judges Order by referringJudge") 
                or die(mysql_error());  
		$select = "<select name=\"judgeId\">\n<option></option>";
		while($row = mysql_fetch_array( $result ))
		{
			if($val == $row['judgeId']){
				$select .="\t<option selected='selected'>".$row['referringJudge']."   *".$row['judgeId']."</option>\n";
			}
			else{		
			   $select .="\t<option>".$row['referringJudge']."   *".$row['judgeId']."</option>\n";
			 }
		}
		$select .= "</select>";
		echo $select;
 }
 
 function DateSelect($val)
 {
 
	$aDate_parts = preg_split("/[\s-]+/", $val);
	//print_r($aDate_parts);
	$curr_month = $aDate_parts[1];
	$curr_day = $aDate_parts[2];
	$curr_year = $aDate_parts[0];
	$month = array (1=>"Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec ");
	$day_today = range(1,31);
	$year = range(1900,2020);
	//show month selection
	$select = "<select name=\"month\">\n";
	foreach ($month as $key => $val) {
		$select .= "\t<option val=\"".$key."\"";
		if ($key == $curr_month) {
			$select .= " selected=\"selected\">".$val."</option>\n";
		} else {
			$select .= ">".$val."</option>\n";
		}
	}
	$select .= "</select>";
	echo $select;
	//show day selection
	$select = "<select name=\"day\">\n";
	foreach ($day_today as $key => $val) {
		$select .= "\t<option val=\"".$key."\"";
		if ($val == $curr_day) {
			$select .= " selected=\"selected\">".$val."</option>\n";
		} else {
			$select .= ">".$val."</option>\n";
		}
	}
	$select .= "</select>";
	echo $select;
	//show year selection
	$select = "<select name=\"year\">\n";
	foreach ($year as $key => $val) {
		$select .= "\t<option val=\"".$key."\"";
		if ($val == $curr_year) {
			$select .= " selected=\"selected\">".$val."</option>\n";
		} else {
			$select .= ">".$val."</option>\n";
		}
	}
	$select .= "</select>";
	echo $select;	
 }
 
 function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

 function successwindow()
 {
 ?>
	<html>
	<head>
	<link href="default.css" rel="stylesheet" type="text/css" />
	</head>
	<body>
	<div id="fulladmin">
	<div id="simple">
	<center><h1>Mediatrix Database</h1><br>
	<!--<form  action="updatecase.php" method="get"> -->
	<div style="padding:5px; border:0px solid red; color:red;" align="center">Updated! Please click <a href="updatecase.php?id=<?php echo $_SESSION['seedval']; ?>"> continue.. </a></div>
	<!--<input type="hidden" name="id" value="<?php echo $_SESSION['seedval']; ?>" /> -->
	<!-- <center> <input type="submit" value="Continue" /> <center> -->
	<!--</form>-->
	</div>
	</div>
	</body>
	</html>
<?php
	exit;
 }
 
 function renderForm(&$newCaseArr,$code,$error)
 {
 //print_r($newCaseArr);
 
 
 ?>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
 <link href="default.css" rel="stylesheet" type="text/css" />
 <title>Update Case Form</title>
 </head>
 <body>
 <div id="fulladmin">
 <div id='adminleft'>
 <p><center><b>Update Case Form</b></center></p>
 </div>
 <div id='adminright'>
 <center><h1>Case Information</h1><br>
 <table border='0' cellpadding='10'>
   <tr><th>
 <?php
//--move session to top of this code

 // if there are any errors, display them
 if ($error != '')
 {
 echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
 }
 ?> 
 
 <form action="" method="post">
 <div align='left'>
 <table border="0">
 <input type="hidden" name="code" value="<?php echo $code; ?>" />
 <input type="hidden" name="scheduleID" value="<?php echo $newCaseArr['scheduleID']; ?>" />
 <tr><td><strong>Unit Control #:  </strong> </td><td><input type="text" name="controlID" value="<?php echo $newCaseArr['controlID']; ?>" /></td></tr>
 <tr><td><strong>Case Number:     </strong> </td><td><input type="text" name="CaseNo" value="<?php echo $newCaseArr['CaseNo']; ?>" /></td></tr>
 <!-- <tr><td><strong>Case Title:     </strong> </td><td><input type="text" name="casetitle" value="<?php echo $newCaseArr['casetitle']; ?>" /></td></tr> -->
 <tr><td><strong>Plaintiff Name:  </strong> </td><td><input type="text" name="plaintiffName" value="<?php echo $newCaseArr['plaintiffName']; ?>" /></td></tr>
 <!--<tr><td><strong>Plaintiff Lawyer:</strong> </td><td><input type="text" name="plaintiffLawyer" value="<?php echo $newCaseArr['plaintiffLawyer']; ?>" /></td></tr> -->
 <tr><td><strong>Defendant Name:  </strong> </td><td><input type="text" name="defendantName" value="<?php echo $newCaseArr['defendantName']; ?>" /></td></tr>
 <!-- <tr><td><strong>Defendant Lawyer:</strong> </td><td><input type="text" name="defendantLawyer" value="<?php echo $newCaseArr['defendantLawyer']; ?>" /></td></tr> -->
 <tr><td><strong>Nature of Case:  </strong> </td><td><?php GetNatureCase($newCaseArr['natureOfCase']); ?></td></tr>
 <tr><td><strong>Type of Case:    </strong> </td><td><?php GetTypeCase($newCaseArr['typeId']); ?></td></tr>
 <tr><td><strong>Judge Name:      </strong> </td><td><?php GetJudge($newCaseArr['judgeId']); ?></td></tr>
 <tr><td><strong>Active:</strong></td><td>
 <select name="caseStatus">
	<option value="Yes" <?php if($newCaseArr['caseStatus'] == "Yes") echo 'selected="selected"'; ?> >Yes</option>
	<option value="No" <?php if($newCaseArr['caseStatus'] == "No") echo 'selected="selected"'; ?> >No</option>
</select></td></tr></table>

<center><h1>Hearing Schedule and Mediator</h1></center><br>
 <table border="0">
 <tr><td><strong>Date (mm/dd/yyyy):</strong> </td><td><?php DateSelect($newCaseArr['Date']); ?><input type="checkbox" name="newdate" value="newsched" /> New Schedule?</td></tr>
  <tr><td><strong>Mediator:</strong> </td><td><?php GetMediator($newCaseArr['mediatorId']); ?></td></tr>
  <tr><td><strong>Comments:</strong></td><td>
		<textarea rows="5" cols="20" wrap="physical" name="Comments"><?php echo $newCaseArr['Comments']; ?> </textarea></td></tr>
 <tr><td><strong>Mediation status:</strong></td><td>
 <select name="status">
	<option value="Ongoing" <?php if($newCaseArr['status'] == "Ongoing") echo 'selected="selected"'; ?> >On Going</option>
	<option value="failed" <?php if($newCaseArr['status'] == "failed") echo 'selected="selected"'; ?> >Failed</option>
	<option value="settled" <?php if($newCaseArr['status'] == "settled") echo 'selected="selected"'; ?> >Settled</option>
<!--	<option value="backtocourt" <?php if($newCaseArr['status'] == "backtocourt") echo 'selected="selected"'; ?> >Back to court</option> -->
</select></td></tr></table>
<br><br><center>
 <input type="submit" name="submit" value="Submit">
 <input type="submit" name="back" value="Back">
  </center> </th></tr></table>
 </div>
 </form> 
 </div>
 <div id="footer"><center>Return to main <a href="dashboard.php"><font color="red">Dashboard</font></a>, or you can <a href="log_out.php?id=<?php echo $_SESSION['userid']; ?>"><font color="red">Log Out</font></a></center></div>

 </body>
 </html>
 <?php 
 }
 
 

 

 // connect to the database
 include('connect-db.php');
 
 // check if the form has been submitted. If it has, start to process the form and save it to the database
 if (isset($_POST['submit']))
 { 
	$temp = array();
	$temp = $_POST;
	


 // get form data, making sure it is valid
    $code = $_POST['code'];
	$ucno = mysql_real_escape_string(htmlspecialchars($_POST['controlID']));
	$caseno = mysql_real_escape_string(htmlspecialchars($_POST['CaseNo']));
	//$casetitle = mysql_real_escape_string(htmlspecialchars($_POST['casetitle']));
	$plaintiffname = mysql_real_escape_string(htmlspecialchars($_POST['plaintiffName']));
	//$plaintifflawyer = mysql_real_escape_string(htmlspecialchars($_POST['plaintiffLawyer']));
	$defendantname = mysql_real_escape_string(htmlspecialchars($_POST['defendantName']));
	//$defendantlawyer = mysql_real_escape_string(htmlspecialchars($_POST['defendantLawyer']));
	$natureofcase = mysql_real_escape_string(htmlspecialchars($_POST['natureOfCase']));
	$typeofcase = mysql_real_escape_string(htmlspecialchars($_POST['typeId']));
	$judgename = mysql_real_escape_string(htmlspecialchars($_POST['judgeId']));
	$mediatorname = mysql_real_escape_string(htmlspecialchars($_POST['mediatorId']));
	$month = mysql_real_escape_string(htmlspecialchars($_POST['month']));
	$day = mysql_real_escape_string(htmlspecialchars($_POST['day']));
	$year = mysql_real_escape_string(htmlspecialchars($_POST['year']));
	$casestatus = mysql_real_escape_string(htmlspecialchars($_POST['caseStatus']));
	$mediationstatus = mysql_real_escape_string(htmlspecialchars($_POST['status']));
	$comments = mysql_real_escape_string(htmlspecialchars($_POST['Comments']));
	$schedID = $_POST['scheduleID'];
	
	
	if(isset($_POST['newdate'])){
		$newdatetick = $_POST['newdate'];
	}
	else $newdatetick = "oldie";
	
	//print_r($_POST);
	//---date conversion----
	$datestring = $month." ".$day." ".$year;
	$tm = strtotime($datestring);
	$hearingdate = date('Y-m-d',$tm);
	//echo $hearingdate;
	//datelog
	$today = date('Y-m-d');
	//echo $today;
	 //--- date reconstruction for passing to form for error
	 //$datereconstruct = $year."-".$month."-".$day;
	$datereconstruct= $hearingdate;
	 
	if ($caseno == '' || $judgename == '' || $mediatorname=='' || $ucno == '')
	{
	// generate error message
		$error = 'ERROR 404: Please fill in all required fields!';
 
	// if either field is blank, display the form again
	//$newCaseArray = $_POST;
	//print_r ($newCaseArray);
// for debugging only
		$i=0;
		foreach ($_POST as $var => $value) { 
			$newCaseArray[$i] = $value;
		//echo "new case =$newCaseArray[$i]<br>";
		//echo "$var = $value<br>"; 
			$i++;
		} 
	    //print_r ($newCaseArray);
		
		renderForm($_POST,$code,$error);
	}
	else
	{
	//-- get Ids for mediator,nature of case, type of case and judge--
		$judgeselect = explode("*",$judgename);
		$mediatorselect = explode("*",$mediatorname);
		$typeofcaseselect = explode("*",$typeofcase);
		$natureofcaseselect = explode("*",$natureofcase);
		
		//echo $judgeselect[IDS];

		//echo "jullibee";
 
	 // connect to the database
		include('connect-db.php');
	// verify case first the existence
		$sql_script = 'SELECT casereferred.controlID, casereferred.CaseNo,casereferred.typeId,casereferred.natureOfCase,casereferred.judgeId,casereferred.mediatorId,casereferred.dateRegister,';
		$sql_script .='casereferred.plaintiffName,casereferred.defendantName,casereferred.caseStatus,';
		$sql_script .= "schedule.Date,schedule.status,schedule.Comments,  casereferred.ControlNo FROM casereferred,schedule WHERE casereferred.CaseNo='".$caseno."' AND schedule.caseNo='".$caseno."'";
		//$sql_script .= " AND schedule.Date=(SELECT MAX(schedule.Date) FROM schedule)";
		//$sql_script = 'SELECT * FROM casereferred WHERE CaseNo="'.$caseno.'"';

		$result = mysql_query($sql_script)	or die(mysql_error()); 

		$row = mysql_num_rows($result);
		
		$row_data = mysql_fetch_array($result);
		
	   //print_r($row_data);
	   //--- fill the index data for form pull down menu
	   	$temp['judgeId']= $judgeselect[IDS];
		$temp['natureOfCase']= $natureofcaseselect[IDS];
		$temp['typeId'] = $typeofcaseselect[IDS];
		$temp['caseStatus'] = $casestatus;
		$temp['mediatorId'] = $mediatorselect[IDS];
		$temp['status'] = $mediationstatus;
		$temp['Date'] = $datereconstruct;

		
		if($newdatetick == "newsched"){
			$new_hearing = date('Y-m-d',strtotime($datereconstruct));
			if($row_data['Date'] == $new_hearing){
				$error = 'ERROR 400: New schedule is the same as the previous schedule';
						
				renderForm($temp,$code,$error);
				exit;
			}
		}

		if (($row>0) && ($row_data['ControlNo'] != $_GET['code'])){
				//$temp = mysql_fetch_array($result);
				$error = 'ERROR: CaseNo.'.$caseno.' has been already exist! Please correct the Case Number!';
				//correcting pulldown menu
/*			$temp['judgeId']= $judgeselect[IDS];
			$temp['natureOfCase']= $natureofcaseselect[IDS];
			$temp['typeId'] = $typeofcaseselect[IDS];
			$temp['caseStatus'] = $casestatus;
			$temp['mediatorId'] = $mediatorselect[IDS];
			$temp['status'] = $mediationstatus;
			$temp['Date'] = $datereconstruct; 
*/
			//print_r($temp);
			
				renderForm($temp,$code,$error);
		}
		else{
			//double check if case is active and not mediation is not settled
			if((strtolower($temp['status']) == "settled") && (strtolower($temp['caseStatus']) == "yes")){
					$error = "ERROR 400 Bad Request: Please inactive the case if mediation is settled.";
					renderForm($temp,$code,$error);
					exit;			
			}

			if((strtolower($temp['status']) == "ongoing") && (strtolower($temp['caseStatus']) == "no")){
					$error = "ERROR 400 Bad Request: Please Active the case if mediation is ongoing.";
					renderForm($temp,$code,$error);
					exit;			
			}
				

			if($newdatetick == "newsched")
			{
				if((strtolower($temp['status']) == "ongoing") && (strtolower($temp['caseStatus']) == "yes")){
				//update date recent date to "reset" status as flag for skipping report generator
				 
					$sql_script = "UPDATE schedule SET status='reset'WHERE scheduleID=".$schedID;
					mysql_query($sql_script) or die(mysql_error()); 	
				//insert new date
					$sql_script = "INSERT INTO schedule (caseNo, Date, status,Comments) ";
					$sql_script .= "VALUES ('".$caseno."','".$new_hearing."','".$mediationstatus."','".$comments."')";

					mysql_query($sql_script) or die(mysql_error()); 			
			
					
					$sql_script = "UPDATE casereferred ";
					$sql_script .= "SET casereferred.controlID = '".$ucno."', casereferred.CaseNo = '".$caseno."', casereferred.typeId = ".$typeofcaseselect[IDS].", casereferred.natureOfCase = ".$natureofcaseselect[IDS].",";
					$sql_script .= "casereferred.judgeId = ".$judgeselect[IDS].", casereferred.mediatorId = ".$mediatorselect[IDS].", casereferred.plaintiffName='".$plaintiffname."',";
					$sql_script .= " casereferred.defendantName = '".$defendantname."',";
					$sql_script .= "casereferred.caseStatus='".$casestatus."'";
					$sql_script .= " WHERE casereferred.ControlNo = $code ";	
				}
				else{
					$error = "ERROR 400 Bad Request: Please make sure case is active and mediation status is on going.";
					renderForm($temp,$code,$error);
					exit;
				}
			}	
			else
			{
					$sql_script = "UPDATE casereferred INNER JOIN schedule ON casereferred.CaseNo = schedule.caseNo ";
					$sql_script .= "SET casereferred.controlID = '".$ucno."', casereferred.CaseNo = '".$caseno."', casereferred.typeId = ".$typeofcaseselect[IDS].", casereferred.natureOfCase = ".$natureofcaseselect[IDS].",";
					$sql_script .= "casereferred.judgeId = ".$judgeselect[IDS].", casereferred.mediatorId = ".$mediatorselect[IDS].", casereferred.plaintiffName='".$plaintiffname."',";
					$sql_script .= " casereferred.defendantName = '".$defendantname."',";
					$sql_script .= "casereferred.caseStatus='".$casestatus."', schedule.CaseNo='".$caseno."', schedule.Date='".$hearingdate."', schedule.status='".$mediationstatus."',";
					$sql_script .= "schedule.Comments= '".$comments."'";
					$sql_script .= " WHERE casereferred.ControlNo = $code AND schedule.scheduleID =$schedID";
			}
			
			//echo $sql_script;

			mysql_query($sql_script) or die(mysql_error()); 
			
			successwindow();
		}
	}
 }
 else
 // if the form hasn't been submitted, display the form
 {
  $error = '';
    if(isset($_POST['back']))
	   header("Location: dashboard.php");
	else{
			//get the code first
		   $controlno = $_GET['code'];
		   $case=$_GET['case'];
		   error_reporting(E_ALL);
	       include('connect-db.php');
		   //reload the correct data
		    $sql_script = "SELECT MAX(schedule.Date) FROM schedule INNER JOIN casereferred ON casereferred.CaseNo=schedule.caseNo WHERE casereferred.CaseNo='".$case."'";
		    $result = mysql_query($sql_script) or die(mysql_error()); 
			$row = mysql_fetch_array($result);
			
			$schedule= $row['MAX(schedule.Date)'];
			//echo $schedule;
			//exit;
			
			$sql_script = 'SELECT casereferred.controlID, casereferred.CaseNo,casereferred.typeId,casereferred.natureOfCase,casereferred.judgeId,casereferred.mediatorId,casereferred.dateRegister,';
			$sql_script .='casereferred.plaintiffName,casereferred.defendantName,casereferred.caseStatus,';
			$sql_script .= "schedule.Date,schedule.status,schedule.Comments, schedule.scheduleID FROM ";
			$sql_script .= "casereferred INNER JOIN schedule ON casereferred.CaseNo = schedule.caseNo WHERE ";
			$sql_script .= "schedule.Date='".$schedule."' AND casereferred.CaseNo ='".$case."'";
			//$sql_script .= "casereferred.CaseNo='".$case."'";
			//$sql_script .= "casereferred,schedule WHERE casereferred.ControlNo=".$controlno." AND casereferred.CaseNo = schedule.caseNo";
            //$sql_script .= " AND schedule.Date=(SELECT MAX(schedule.Date) FROM schedule)";
			
			//echo  $sql_script;
			//exit;
			$result = mysql_query($sql_script) or die(mysql_error()); 
			$row = mysql_fetch_array($result);
			//print_r($row);
			//exit;
			renderForm($row,$controlno,$error);
	  }
 }
?> 